package com.wyvoid.forum.web.action.admin;

import com.wyvoid.forum.web.action.BaseAction;
import com.wyvoid.forum.domain.User;
import com.wyvoid.forum.domain.SessionAdmin;
import com.wyvoid.forum.service.IUserService;
import com.wyvoid.forum.exception.admin.AdminLoginFailureException;
import com.wyvoid.forum.Constant;
import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.*;
import org.apache.commons.lang.StringUtils;

import java.util.Date;

/**
 * User: cjp
 * Date: 2007-5-23
 * Time: 13:11:32
 */
@UrlBinding(value="/admin/login.do")
public class LoginAction extends BaseAction {
     @ValidateNestedProperties({
    @Validate(field = "username", required = true, minlength = 2, maxlength = 32),
    @Validate(field = "password", required = true, minlength = 4, maxlength = 16)
            })
    private User admin;
    @SpringBean
    private IUserService userService;
    @Validate(required = true, minlength = 4, maxlength = 4)
    private String validateCode;
    public User getAdmin() {
        return admin;
    }

    public void setAdmin(User admin) {
        this.admin = admin;
    }

    public String getValidateCode() {
        return validateCode;
    }

    public void setValidateCode(String validateCode) {
        this.validateCode = validateCode;
    }

    public void setUserService(IUserService userService) {
        this.userService = userService;
    }

    @DontValidate
    public Resolution loginForm(){
        return getAdminResolution("loginForm");
    }

    @DefaultHandler
    public Resolution login(){
        try{
            User tempAdmin=userService.authLogin(admin.getUsername(), admin.getPassword());
            SessionAdmin sessionAdmin=new SessionAdmin(tempAdmin.getId(),tempAdmin.getNickname());
            sessionAdmin.setLastLoginTime(tempAdmin.getLastLoginTime());
            context.getRequest().getSession().setAttribute(Constant.SESSION_ADMIN_KEY, sessionAdmin);
            tempAdmin.setLastLoginIp(context.getRequest().getRemoteAddr());
            tempAdmin.setLastLoginTime(new Date());
            userService.updateUser(tempAdmin);
        } catch (AdminLoginFailureException e) {
            getContext().getValidationErrors().add("loginFailure", new SimpleError("登录失败"));
            return getContext().getSourcePageResolution();
        }
        return new RedirectResolution("/admin/index.do");
    }
    @ValidationMethod(on = "login")
    public void confirmValidateCode(ValidationErrors errors) {
        if (!StringUtils.equals(validateCode, (String) context.getSessionAttribute("validateCode"))) {
            errors.add("validateCode", new SimpleError("验证码填写错误"));
        }
    }
}
